package Service;

import Pojo.Account;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public  class AccountService {

    public List<Account> lodingAccountAll() {
        List<Account> list = new ArrayList<>();
        try {
            BufferedReader br = new BufferedReader(new FileReader("D:\\Demo123\\src\\image\\Reader.txt"));
            String line = null;
            while ((line = br.readLine()) != null) {
                /* System.out.println(line);*/
                String[] aray = line.split(",");
                Account account = new Account();
                account.setId(aray[0].trim());
                account.setUsername(aray[1].trim());
                account.setPassword(aray[2].trim());
                list.add(account);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return list;
    }
    public String[][] listToArray(List<Account> list){
        String[][] obj = new String[list.size()][3] ;
        for (int i = 0 ; i< list.size(); i++){
            Account account = list.get(i);
            obj[i] = new String[]
                    {account.getId(),account.getUsername(),account.getPassword()};
        }
        return obj ;
    }
    public void saveAccount(String name ,String pwd){
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\Demo123\\src\\image\\Reader.txt",true));
            String line = maxId()+","+name +","+pwd ;
            bw.newLine();
            bw.write(line);
            bw.flush();
//bw.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    public int maxId(){
        int maxId = 0 ;
        List<Account> list = lodingAccountAll();
        for(int i= 0 ; i < list.size() ; i++){
            int id = Integer.parseInt(list.get(i).getId());
            if(id > maxId){
                maxId = id ;
            }
        }
        return maxId+1;
    }
    public void delAccount(int id){
        List<Account> list = lodingAccountAll();
        list.remove(id);
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\Demo123\\src\\image\\Reader.txt"));
            for(int i = 0 ; i < list.size() ; i++){
                String line = list.get(i).getId()+","+list.get(i).getUsername()+","+list.get(i).getPassword();
                bw.write(line);
                if(i != list.size() -1){
                    bw.newLine();
                }
            }
            bw.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

